Thumb

JavaScript Array Iteration Methods

1/22/2020 12:00:00 AM

JavaScript have Iteration methods which is responsible to code are more easily write for the programmer. This method is help to array representation by our need. If we filter the array and find the specie value from the array then we write lop. This is so difficult every time write loop according our need. We can filter method and find our specific value from the array. Also, we can perform the loop by using “forEach” on the array. We have eight iteration method to help to write our code. Our iteration methods are given bellow:
•    forEach
•    map
•    filter
•    reduce
•    some
•    every
•    find
•    find index

Now given bellow example the code and explain the code:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">

// forEach
var threeNum = [1, 2, 3];
threeNum.forEach(function (item, index) {
  console.log(item, index);
});

// map
const three = [1, 2, 3];
const doubled = three.map(function (item) {
  return item * 2;
});
console.log(doubled);


// filter
const ints = [1, 2, 3];
const evens = ints.filter(function (item) {
  return item % 2 === 0;
});
console.log(evens);


// reduce
const sum = [1, 2, 3].reduce(function (result, item) {
  return result + item;
}, 0);
console.log(sum)


// some
const hasNegativeNumbers = [1, 2, 3, -1, 4].some(function (item) {
  return item < 0;
});
console.log(hasNegativeNumbers);


// every
const allPositiveNumbers = [1, 2, -3].every(function (item) {
  return item > 0;
});
console.log(allPositiveNumbers);


// find
const objects = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
const found = objects.find(function (item) {
  return item.id === 'b';
});
console.log(found);


// find index
const objects2 = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
const foundIndex = objects2.findIndex(function (item) {
  return item.id === 'b';
});
console.log(foundIndex)

</script>
</body>
</html>

In this code we see some Iteration Methods and we see the method are how to work on the array. This method is very helpful for programmer. Programmer can easily find, sort, filter etc perform using this predefine function or method.